<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Profile extends CI_Controller {
	var $gallery_path;
	function __construct(){
		parent::__construct();
		(!session_id()) ? session_start() : '';
		$this->load->model('users_model');
		$this->load->model('recipients_model');
		$this->load->model('messages_model');
		$this->load->model('posts_model');
		$this->load->helper('myuser_helper');
		$this->load->library('encryption_lib');
		$this->load->helper('boolean_helper');
		$this->gallery_path = realpath(APPPATH . '../images');
	}

	public function index($param=null)
	{
		(isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in'] && isset($_SESSION['email']))? '':redirect('home');
		$data['title']			= "Sign in My Life My Eulogy";
		$data['records'] 		= $this->users_model->get_user();
		$usertype = strtolower(Myuser_helper::get_user_type($_SESSION['email']));//vip,free or reseller
		switch($usertype){
			case 'vip':
				$data['main_content'] 	= 'profile/profile_view';break;
			default:
			case 'free':
				$data['main_content'] 	= 'profile/remembrance_wall_view';
				$data['records_wall'] = $this->posts_model->get_remembrance_wall();break;
			case 'reseller':
				$rid = $data['records']->userid;
				$resellerStats = $this->getResellerStats($rid);
				$param = strtolower($param);
				if($param == 'transactions'){
					$data['transactions'] = $this->getResellerTransac($rid);
					$data['main_content'] 	= 'profile/reseller/reseller_transactions_view';
				}elseif($param == 'accounts'){
					$data['resellerStats'] = $resellerStats;
					$data['accounts'] = $this->getResellerAccounts($rid);
					$data['main_content'] 	= 'profile/reseller/reseller_accounts_view';
				}else{
					$data['resellerStats'] = $resellerStats;
					$data['main_content'] 	= 'profile/reseller/reseller_home_view';
				}
				$data['usertype'] = 'reseller';
				break;
		}//end switch
		$data['numPhotos'] 		= $this->messages_model->countMessages("photos");
		$data['numVideos'] 		= $this->messages_model->countMessages("videos");
		$data['numNotes'] 		= $this->messages_model->countMessages("notes");
		$data['numDocuments']	= $this->messages_model->countMessages("documents");
		$data['numJournal'] 	= $this->messages_model->countMessages("journal");
		$data['bottom_ads'] 	= Myuser_helper::getAds('bottom',1);
		$this->load->view('include/template', $data, array('error' => ''));

	}

	function remembrance_wall(){
		(isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in'] && isset($_SESSION['email']))? '':redirect('home');
		$data['title']= "My Life My Eulogy | Remembrance Wall";
		$data['records'] 		= $this->users_model->get_user();
		$data['main_content'] = 'profile/remembrance_wall_view';
		$data['user_info'] 		= $data['records'];
		$this->load->library('pagination');
		$start_row = $this->uri->segment(4);
		$limit = 5;
		if(trim($start_row) == ""){
			$start_row = 0;
		}
		$config['base_url'] = site_url('profile/remembrance_wall/page');
		$config['total_rows'] =  count($this->posts_model->get_remembrance_wall());
		$config['per_page'] = $limit;
		$config['uri_segment'] = 4;
		$config['anchor_class'] = 'class="button pagi" ';
		$this->pagination->initialize($config);
		$data['pagination'] = $this->pagination->create_links();
		
		$data['records_wall'] = $this->posts_model->get_remembrance_wall($start_row,$limit);
		
		$this->load->view('include/template', $data);
	}
	function get_days_per_month(){
		$post = $this->input->post();
		(empty($post))? redirect('profile'):'';
		$output = '';
		$month = $this->input->post('month');
		$sel_id = ($this->input->post('id') == 'sel_birthday_month')? 'sel_birthday_day':'sel_death_day';
		$n_days = cal_days_in_month(CAL_GREGORIAN, $month, 1960);
		$output .= '<select name="'.$sel_id.'" id="'.$sel_id.'">';
			$output .= '<option value="">Day</option>';
				for($day=1;$day<=$n_days;$day++){
					$output .= '<option value="'.$day.'">'.$day.'</option>';
				}
		$output .= '</select>';
		echo $output;
	}//end fct
	function save_remembrance_wall(){
		$post = $this->input->post();
		(empty($post))? redirect('profile'):'';
		$output = '';
		$user_info = $this->users_model->get_user();

		$birthday = $post['sel_birthday_year'].'-'.str_pad($post['sel_birthday_month'],2,"0",STR_PAD_LEFT).'-'.str_pad($post['sel_birthday_day'],2,"0",STR_PAD_LEFT);
		$date_of_death = $post['sel_death_year'].'-'.str_pad($post['sel_death_month'],2,"0",STR_PAD_LEFT).'-'.str_pad($post['sel_death_day'],2,"0",STR_PAD_LEFT);
		$c_date = date('Y-m-d H:i:s');
		$save = $this->posts_model->save_remembrance_wall($post,$c_date,$birthday,$date_of_death);
		if($save){
			$output .= '<div class="rem_msg_content">';
				$image = (!empty($user_info->picture))? $user_info->picture:'default.png';
				$output .= '<div class="recipient-thumbs fleft"><img src = "'.base_url().'assets/images/'.$image.'"/></div>';
				$output .= '<div class="fleft">';
					$output .= '<div class ="rem_name">'.$post['uname'].'</div>';
					$output .= '<div class="rem_virtual_wrapper">';
						if(!empty($post['file_name'])):
							$output .= '<div class="fleft mright10"><img src="'.$post['file_name'].'" alt="message file" class="virtual_fl"/></div>';
						endif;
						$output .= '<div class="rem_msg fleft">'.$post['add-remwall-msg'].'</div>';
						$output .= '<div class="clear"></div>';
					$output .= '</div>';
					$output .= '<div class="rem_posted">';
						if(!empty($post['file_name'])):
							$output .= '<div class="rem_p_icon fleft"></div>';
						endif;
						$output .= '<div class="fleft rem_date">'.date('F j, Y, g:i a',strtotime($c_date)).'</div>';
						$output .= '<div class="clear"></div>';
					$output .= '</div>';
					$output .= '<div class="rem_posted">';
						$output .= '<div class="fleft">Posted to:</div>';
						$output .= '<div class="postedto_icon fleft"></div>';
						$output .= '<div class="f999 fleft">'.$post['add-remwall-name'].'</div>';
						$output .= '<div class="cal_icon fleft"></div>';
						$output .= '<div class="fleft">'.date('M d, Y',strtotime($birthday)).' - '.date('M d, Y',strtotime($date_of_death)).'</div>';
						$output .= '<div class="clear"></div>';
					$output .= '</div>';
				$output .= '</div>';
				$output .= '<div class="clear"></div>';
			$output .= '</div>';
		}else{
			$output .= '0';
		}
		echo $output;
	}

	function update_profile(){
		$post = $this->input->post();
		(empty($post))? redirect('profile'):'';
		$bdate = $this->input->post('dob');
		$query = (empty($bdate))? $this->users_model->edit_profile($post):$this->users_model->edit_profile(array('dob'=>date('Y-m-d',strtotime($bdate))));
		if(empty($bdate)){
			echo ($query)? 'true':'false';
		}else{
			echo date('F m, Y',strtotime($bdate));
		}
		return $query;
	}
	function update_picture(){
		$newfilename = md5($_SERVER['REMOTE_ADDR'].rand());
		$config = array(
			'allowed_types' => 'gif|jpg|png|bmp|jpeg',
			'upload_path' =>$_SERVER['DOCUMENT_ROOT'].'/mlme2/assets/images/useruploads/profile_photos/',
			'max_size' => 10000,
			'max_width' => 5000,
			'max_height' => 5000,
			'file_name' => $newfilename
		);
		$this->load->library('upload', $config);
		$this->upload->initialize($config);

		if ( ! $this->upload->do_upload('userpic')){
			$error = array('error' => $this->upload->display_errors());
//print_r($error);
	
			return $error;
		} else {

			$upload = array('upload_data' => $this->upload->data());
			$path = '/useruploads/profile_photos/'.$upload['upload_data']['file_name'];
			$this->users_model->edit_profile(array('picture'=>$path));

			redirect('profile');
		}
	}
	function logout()
	{
		session_destroy();
		redirect('home');
	}
	function eulogy_video($userid=''){
		(isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in'] && isset($_SESSION['email']))? '':redirect('home');
		$data['userinfo'] 		= (strlen($userid) < 43)? $this->users_model->get_user():$this->users_model->get_user_info($userid);
		$data['records'] = $data['userinfo'];
		$data['title']			= "My Life My Eulogy | Eulogy Video";
		$data['main_content'] = 'profile/profile_eulogy_video_view';
		$data['email'] = $_SESSION['email'];
		$this->load->view('include/template', $data);
	}
	function upload_video() {

		if (!empty($_FILES)) {
			$tempFile = $_FILES['Filedata']['tmp_name'];
			$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/mlme2/assets/images/useruploads'. $_REQUEST['folder'] . '/';

			$fileparts = pathinfo($_FILES['Filedata']['name']);
			$newfilename = md5($_SERVER['REMOTE_ADDR'].rand()).'.'.$fileparts['extension'];
			$targetFile =  str_replace('//','/',$targetPath) . $newfilename;
			mkdir(str_replace('//','/',$targetPath), 0755, true);
			move_uploaded_file($tempFile,$targetFile);
			$user_id = $_POST['userid'];
			$this->db->where('userid',$user_id);
			$this->db->update('mlme_users',array('eulogy_video'=>$newfilename));
			$old_video = $_POST['old_video'];
			if(file_exists($targetPath.$old_video) && !empty($old_video)){
				unlink($targetPath.$old_video);
			}
		}else{
			redirect('profile');
		}//end if
	}
	function check_user_password(){
		$post = $this->input->post();
		(empty($post))? redirect('profile'):'';
		$executor = $this->input->post('executor');
		//$checked = $this->users_model->check_recipient_password($post);
		if($executor =='1'){
			$checked = $this->users_model->check_executor_password($post);
		}else{
			$checked = $this->users_model->check_recipient_password($post);
		}
		echo ($checked)? 'true':'false';
	}
	function eulogy($userid=''){
		(isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in'] && isset($_SESSION['email']))? '':redirect('home');
		(strlen($userid) < 43)? redirect('profile'):'';
		$data['title'] = 'Profile';
		$data['records'] = $this->users_model->get_user_info($userid);
		$data['recipient_info'] = Myuser_helper::get_recipient_user_id($_SESSION['email']);//get the user id and recipient id
		if(count($data['recipient_info']) > 0){
			$data['messages1'] = Myuser_helper::get_freeuser_messages($data['recipient_info'],false,$userid);//message that is public or all totype
			$data['messages2'] = Myuser_helper::get_freeuser_messages($data['recipient_info'],true,$userid);//message for specific
		}else{
			redirect('profile');
		}
		$data['main_content'] 	= 'profile/eulogy_messages_view';
		$data['bottom_ads'] 	= Myuser_helper::getAds('bottom',1);
		$this->load->view('include/template', $data);
	}
	function edit(){
		(isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in'] && isset($_SESSION['email']))? '':redirect('home');
		$data['save'] = false;
		if(isset($_POST['ep-submit'])){
			$post_data = array();
			$post = $this->input->post();
			(!empty($post['firstname']))? $post_data['firstname'] = $post['firstname']:'';
			(!empty($post['middle']))? $post_data['middle'] = $post['middle']:'';
			(!empty($post['lastname']))? $post_data['lastname'] = $post['lastname']:'';
			(!empty($post['password']))? $post_data['password'] = $post['password']:'';
			$post_data['dob'] = (!empty($post['dob']))? date('Y-m-d',strtotime($post['dob'])):'';
			$post_data['about'] = $post['about'];
			$data['save'] = ($this->users_model->edit_profile($post_data))? true:false;
		}
		$data['title'] = 'Edit Profile';
		$data['records'] 		= $this->users_model->get_user();
		$data['main_content'] 	= 'profile/profile_edit_settings_view';
		$data['bottom_ads'] 	= Myuser_helper::getAds('bottom',1);
		$this->load->view('include/template', $data);
	}
	//get Reseller statistics
	//params int : userid
	//return object
	function getResellerStats($userid){
		//check if userid is a reselleer else return false
		$CI = &get_instance();
	 	$CI->db->select('userid');
	 	$CI->db->where('type','reseller');
	 	$qry = $CI->db->get('mlme_users');
		if($qry->num_rows < 0){
			return false;
		}
		$stats = null;
		$CI = &get_instance();
	 	$CI->db->select('COUNT(userproductid) as numPackages');
	 	$CI->db->where('userid', $userid);
	 	$qry = $CI->db->get('mlme_usersproduct')->result();
	 	$stats->numPackages = $qry[0]->numPackages;

		$CI = &get_instance();
	 	$CI->db->select('SUM(accounts_qty) as numAccounts');
	 	$CI->db->where('userid', $userid);
	 	$CI->db->where('status', 1);
	 	$qry = $CI->db->get('mlme_usersproduct')->result();
	 	$stats->numAccounts = $qry[0]->numAccounts;

		$CI = &get_instance();
		$qstr = "SELECT COUNT(a.customerid) as numRegistered FROM mlme_usersproduct_customers a, mlme_usersproduct b" .
				" WHERE a.userproductid=b.userproductid " .
				" AND b.userid = $userid";
	 	$qry = $CI->db->query($qstr);
	 	$result = $qry->result();
	 	$stats->numRegistered = $result[0]->numRegistered;

		$stats->numRemaining = (int)$stats->numAccounts - (int)$stats->numRegistered;

		return $stats;
	}
	//get the order record of the reseller
	//@param int: id of the user
	//return array of object
	function getResellerTransac($userid){
		$qstr = "SELECT a.order_number, a.date_created, b.name, a.order_currency, a.order_total, a.order_status, c.code" .
				" FROM mlme_orders a, mlme_products b, mlme_usersproduct c" .
				" WHERE a.userid=$userid AND" .
				" a.productid=b.productid AND" .
				" b.productid=c.productid";
		return $this->db->query($qstr)->result();
	}
	//get the accounts data of the reseller
	//@param int: id of the user
	//return array of object
	function getResellerAccounts($userid){
		$qstr = "SELECT a.code, a.status, b.customerid, c.firstname, c.middle, c.lastname, c.date_added, c.email" .
				" FROM mlme_usersproduct a, mlme_usersproduct_customers b, mlme_users c" .
				" WHERE a.userid=$userid" .
				" AND a.userproductid=b.userproductid" .
				" AND b.customerid=c.userid";
		return $this->db->query($qstr)->result();
	}
}// end of controller







